package org.opencare.ndwc.persistence;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.opencare.ndwc.model.EventLevel;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class JpaEventLevelDao implements EventLevelDao {

	@PersistenceContext
	private EntityManager em;

	@Override
	public EventLevel find(Long id) throws DataAccessException {
		// TODO Auto-generated method stub
		return em.find(EventLevel.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<EventLevel> findAll() throws DataAccessException {
		// TODO Auto-generated method stub
		
		Query ql = em.createQuery("select e from EventLevel e order by e.id desc");
		List<EventLevel> result = ql.getResultList();
		
		return result;
	}

	@Override
	public EventLevel findEventLevelByLevelName(String levelName)
			throws DataAccessException {
		// TODO Auto-generated method stub
		
		Query ql = em.createQuery("select e from EventLevel e where e.level = :levelName");
		ql.setParameter("levelName", levelName);
				
		return (EventLevel) ql.getSingleResult();
	}
	
	@Transactional
	@Override
	public void save(EventLevel eventLevel) throws DataAccessException {
		// TODO Auto-generated method stub
		if (eventLevel.getId() == null) {
			em.persist(eventLevel);
		} else {
			em.merge(eventLevel);
		}
	}

	@Transactional
	@Override
	public void remove(Long id) throws DataAccessException {
		// TODO Auto-generated method stub
		EventLevel e = find(id);
		if (e != null) {
			em.remove(e);
		}
	}
	
	@Override
	public void removeAll() throws DataAccessException {
		// TODO Auto-generated method stub
		em.createQuery ("delete from EventLevel").executeUpdate();
	}

	@Override
	public Long countEventLevel() throws DataAccessException {
		// TODO Auto-generated method stub
		
		Query ql = em.createQuery("select count(e) from EventLevel e");
		
		return (Long) ql.getSingleResult();
	}



}
